package com.asset.modules.assets.service.impl;

import com.asset.modules.assets.mapper.AssetMapper;
import com.asset.modules.assets.model.Asset;
import com.asset.modules.assets.service.AssetService;
import com.asset.modules.common.servcie.CodeService;
import com.asset.modules.common.utils.Calcutil;
import com.asset.modules.common.utils.CodeGenerator;
import com.asset.modules.common.utils.StringUtil;
import com.asset.modules.system.model.Company;
import com.asset.modules.system.model.Project;
import com.asset.modules.system.service.CompanyService;
import com.asset.modules.system.service.ProjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author asset
 * @since 2020-08-13
 */
@Service
public class AssetServiceImpl extends ServiceImpl<AssetMapper, Asset> implements AssetService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AssetServiceImpl.class);

    @Autowired
    ProjectService projectService;

    @Autowired
    CompanyService companyService;

    public boolean mySaveOrUpdate(Asset asset){
        String price = String.valueOf(asset.getRegisterMoney());
        String date  = asset.getBuyTime();
        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        //每次修改或者保存的时候，计算净值
        try {
            double value =  Calcutil.calcValue(price, date, asset.getTotalYear(), currentDate);
            asset.setValue(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //判断盘点数量，如果为空，则置为0
        if(asset.getCheckNum()==null){
            asset.setCheckNum(0L);
        }
        //如果使用年限为0，则设置其为5
//        if(asset.getTotalYear()==0){
//            asset.setTotalYear(5);
//        }

        String[] times = asset.getBuyTime().split("T");
        if(times.length>0){
            asset.setBuyTime(times[0]);
        }

        //计算盈亏，与盘点数量和采购总量有关
        double earnValue = Calcutil.calcEarn(asset.getRegisterNum(), asset.getRegisterMoney(), asset.getCheckNum());
        asset.setEarnMoney(earnValue);
        if(asset.getManageCode()==null||asset.getManageCode().equals("")){
            asset.setManageCode(CodeGenerator.generateManageCode(asset.getProjectCode()));
        }
        LOGGER.info("当前的固资状态为:"+ asset.getStatus());
        return saveOrUpdate(asset);
    }


    /**
     * 获取固资分页数据
     * @param page
     * @param asset
     * @return
     */
    @Override
    public IPage<Asset> getAssetPage(Page page,  Asset asset) {
        QueryWrapper<Asset> qw = new QueryWrapper<>();
        String status = asset.getStatus();
        if(asset.getUpdateTime()!=null&&asset.getCreateTime()!=null){
            qw.ge("buy_time", getDate(asset.getCreateTime()));
            qw.le("buy_time", getDate(asset.getUpdateTime()));
        }
        if(status==null||status.equals("")){
            qw.between("status", "0", "1");
        }else{
            qw.eq("status",status);
        }
        return this.getPages(page, qw, asset);
    }

    /**
     * 获取低值易耗品分页数据
     * @param page
     * @return
     */
    public IPage<Asset> getLowValuePage(Page<Asset> page, Asset asset){
        QueryWrapper<Asset> qw = new QueryWrapper();
        if(asset.getUpdateTime()!=null&&asset.getCreateTime()!=null){
            qw.ge("buy_time",getDate(asset.getCreateTime()));
            qw.le("buy_time",  getDate(asset.getUpdateTime()));
        }
        qw.eq("status", "-2");
        return this.getPages(page, qw, asset);
    }

    /**
     * 获取报废固资分页数据
     * @param page
     * @param asset
     * @return
     */
    public IPage<Asset> getDiscardPage(Page page, Asset asset) {
        QueryWrapper<Asset> qw = new QueryWrapper();
        if(asset.getUpdateTime()!=null&&asset.getCreateTime()!=null){
            qw.ge("buy_time",getDate(asset.getCreateTime()));
            qw.le("buy_time",  getDate(asset.getUpdateTime()));
        }
        qw.eq("status", "-1");
        return this.getPages(page,qw, asset);
    }


    /**
     * 获取固资信息公共接口
     * @param page
     * @param qw
     * @param asset
     * @return
     */
    public IPage<Asset> getPages(Page page, QueryWrapper<Asset> qw, Asset asset){
        IPage<Asset> pg;
        Map params = new HashMap();

        String id = asset.getProjectId();
        if(id==null){
            return null;
        }
        Project p = projectService.getById(id);
        if(p==null){
            return null;
        }
        Company c = companyService.getById(p.getCompanyId());
        if(c==null){
            return null;
        }

        if(asset.getCompanyId()!=null && StringUtil.isNotBlank(asset.getCompanyId())){
            params.put("company_id", asset.getCompanyId());
        }


        if(StringUtil.isNotBlank(asset.getProjectId())){
            params.put("project_id", asset.getProjectId());
        }
        if(asset.getDepartment()!=null&&StringUtil.isNotBlank(asset.getDepartment())){
            params.put("department", asset.getDepartment());
        }
        if(asset.getManageCode()!=null&&StringUtil.isNotBlank(asset.getManageCode())){
            params.put("manager_code", asset.getManageCode());
        }
        if(asset.getDeviceName()!=null&&StringUtil.isNotBlank(asset.getDeviceName())){
            params.put("device_name", asset.getDeviceName());
        }

        qw.allEq(params);

        if(asset.getAssetCode()!=null&&StringUtil.isNotBlank(asset.getAssetCode())){

            qw.eq("(asset_code", asset.getAssetCode())
                    .or().eq("card", asset.getAssetCode())
                    .or().eq("manage_code", asset.getAssetCode()).last(")");
        }
        pg = page(page, qw);
        pg.setTotal(count(qw));
        List<Asset> assets = pg.getRecords();
        //如果查询结果不为空，则
        if(assets!=null&&assets.size()>0){
            for(Asset a : assets){
                a.setProjectCode(p.getProjectCode());
                a.setProjectName(p.getProjectName());
                a.setCompanyId(p.getCompanyId());
                a.setCompanyCode(c.getCompanyCode());
                a.setCompanyName(c.getCompanyName());
            }
        }
        return pg.setRecords(assets);
    }


    /**
     * 判断信息是否已经存在
     * @param column
     * @param name
     * @return
     */
    @Override
    public boolean isExist(String column, String name) {
        QueryWrapper<Asset> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, name);
        List result = list(queryWrapper);
        if(result.size()>0){
            return true;
        }
        return false;
    }

    /**
     * 获取当年固定资产统计值
     * @param year
     * @param projectId
     * @return
     */
    @Override
    public double yearlyExpenditure(String year, String projectId) {
        QueryWrapper<Asset> qw = new QueryWrapper<>();
        Double expenditure = null;
        qw.eq("substr(buy_time, 1, 4)", year);
        qw.eq("project_id", projectId);
        qw.select("sum(register_money) as expenditure, project_id, substr(buy_time, 1, 4) as year");
        qw.groupBy("project_id, substr(buy_time, 1, 4)");
        Map map = getMap(qw);
        if(map!=null){
            expenditure = (Double) map.get("expenditure");
            return expenditure;
        }
        return 0;
    }

    /**
     * 根据项目公司ID获取预算信息
     * @param id
     * @return
     */
    @Override
    public List<Asset> getAssetsByProjectId(String id) {
        QueryWrapper<Asset> qw = new QueryWrapper<>();
        qw.eq("project_id", id);
        List<Asset> assets = list(qw);
        return assets;
    }

    public String getDate(LocalDateTime time){
        String tempDate = time.toString();
        String dateStr  = tempDate.split("T")[0];
        return dateStr;
    }
}
